// Wave.cpp: implementation of the CWave class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Game.h"
#include <dsound.h>    // DirectSound
#pragma comment(lib,"dsound.lib")
#pragma comment(lib,"winmm.lib")

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CWave::CWave(char* psFileName)
{
    m_filename = psFileName;
    m_pData = NULL;
    m_size = 0;
    m_valid = LoadFile(psFileName);
}

CWave::~CWave()
{
    if( m_pData != NULL )
        delete [] m_pData;
}

BOOL CWave::IsValid()
{
    return m_valid;
}

DWORD CWave::GetSize()
{
    return m_size;
}

BYTE* CWave::GetData()
{
    return m_pData;
}

char* CWave::GetFilename()
{
    return m_filename;
}

LPWAVEFORMATEX CWave::GetFormat()
{
    return &m_wfe;
}

BOOL CWave::LoadFile(char* psFileName)
{
    MMCKINFO mmCkiRiff;
    MMCKINFO mmCkiChunk;

    HMMIO hMMIO = mmioOpen(psFileName, NULL, MMIO_READ|MMIO_ALLOCBUF );
    if( hMMIO == NULL )
        return FALSE;

    mmCkiRiff.fccType = mmioFOURCC('W','A','V','E');
    MMRESULT mmResult = mmioDescend(hMMIO,&mmCkiRiff,NULL,MMIO_FINDRIFF);
    if( mmResult != MMSYSERR_NOERROR )
        return FALSE;

    mmCkiChunk.ckid = mmioFOURCC('f','m','t',' ');
    mmResult = mmioDescend(hMMIO,&mmCkiChunk,&mmCkiRiff,MMIO_FINDCHUNK);
    if( mmResult != MMSYSERR_NOERROR )
        return FALSE;

    LONG numBytes = mmioRead(hMMIO, (char*)&m_wfe, sizeof(WAVEFORMATEX));
    if( numBytes == -1 )
        return FALSE;

    mmResult = mmioAscend(hMMIO, &mmCkiChunk, 0);
    if( mmResult != MMSYSERR_NOERROR )
        return FALSE;

    mmCkiChunk.ckid = mmioFOURCC('d','a','t','a');
    mmResult = mmioDescend(hMMIO, &mmCkiChunk, &mmCkiRiff, MMIO_FINDCHUNK);
    if( mmResult != MMSYSERR_NOERROR )
        return FALSE;

    m_size = mmCkiChunk.cksize;
    m_pData = new BYTE[ m_size ];
    if( m_pData == NULL )
        return FALSE;

    numBytes = mmioRead(hMMIO, (char*)m_pData, m_size);
    if( numBytes == -1)
        return FALSE;

    mmioClose(hMMIO, 0);

    return TRUE;
}

// END